import { toast } from '~/composables/util';

// 纯前端模拟请求，返回 Promise
const service = {
  // 模拟登录请求
  post: (url, data) => {
    return new Promise((resolve, reject) => {
      if (url === '/login' && data.password === '123456') {
        // 模拟登录成功，返回 token
        resolve({
          token: 'mock_token_' + Date.now(),
          data: {
            id: data.id,
            type: data.type,
            password: data.password
          }
        });
      } else if (url.includes('/info/')) {
        // 模拟获取用户信息
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        resolve({
          code: 200,
          data: { ...user, ...{ mockInfo: '模拟用户信息' } }
        });
      } else if (url === '/update-password') {
        // 模拟修改密码
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        user.password = data.newPassword;
        localStorage.setItem('user', JSON.stringify(user));
        resolve({
          code: 200,
          data: { message: '密码修改成功' }
        });
      } else {
        reject({ response: { data: { message: '请求失败' } } });
        toast('请求失败（模拟）', 'error');
      }
    });
  },
  // 模拟 GET 请求（获取用户信息用）
  get: (url) => {
    return new Promise((resolve, reject) => {
      if (url.includes('/info/')) {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        resolve({
          code: 200,
          data: { ...user, ...{ mockInfo: '模拟用户信息' } }
        });
      } else {
        reject({ response: { data: { message: '请求失败' } } });
        toast('请求失败（模拟）', 'error');
      }
    });
  },
  // 模拟 PUT 请求（更新用户信息用，这里简单模拟）
  put: (url, data) => {
    return new Promise((resolve) => {
      const user = JSON.parse(localStorage.getItem('user') || '{}');
      const updatedUser = { ...user, ...data };
      localStorage.setItem('user', JSON.stringify(updatedUser));
      resolve({
        code: 200,
        data: updatedUser
      });
    });
  }
};

export default service;